import urllib.parse
from abc import ABC,abstractmethod
from fastapi import APIRouter, HTTPException, status, Query, Request
import sys

from starlette.responses import RedirectResponse

from config.dingtalk_config import DINGTALK_CONFIG

DINGTALK_CLIENT_ID = DINGTALK_CONFIG['CLIENT_ID']
DINGTALK_CLIENT_SECRET = DINGTALK_CONFIG['CLIENT_SECRET']
DINGTALK_REDIRECT_URI = DINGTALK_CONFIG['REDIRECT_URI']


class Factory(ABC):
    @abstractmethod
    def geturl(self):
        pass

    @abstractmethod
    def callback(self,code):
        pass


class Qq(Factory):
    def geturl(self):
        # TODO: 实现QQ登录URL生成
        # 这里需要根据QQ开放平台的API文档来实现
        return "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=YOUR_QQ_APP_ID&redirect_uri=YOUR_REDIRECT_URI&state=qq_login"

    def callback(self, code):
        # TODO: 实现QQ登录回调处理
        # 这里需要根据QQ开放平台的API文档来实现
        raise NotImplementedError("QQ登录功能尚未实现")

class Wechat(Factory):
    def geturl(self):
        # TODO: 实现微信登录URL生成
        # 这里需要根据微信开放平台的API文档来实现
        return "https://open.weixin.qq.com/connect/qrconnect?appid=YOUR_WECHAT_APP_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=code&scope=snsapi_login&state=wechat_login"

    def callback(self, code):
        # TODO: 实现微信登录回调处理
        # 这里需要根据微信开放平台的API文档来实现
        raise NotImplementedError("微信登录功能尚未实现")

import requests
class Dingding(Factory):
    def geturl(self):
        auth_url = {
            "client_id": DINGTALK_CLIENT_ID,
            "redirect_uri": DINGTALK_REDIRECT_URI,
            "response_type": "code",
            "scope":DINGTALK_CONFIG['SCOPE'],
            "state":DINGTALK_CONFIG['STATE'],
            "prompt":"consent"
        }
        auth_url =f"{DINGTALK_CONFIG['AUTH_URL']}?{urllib.parse.urlencode(auth_url)}"
        return auth_url  # 返回URL字符串而不是RedirectResponse对象


    def callback(self,authCode):
        print("authCode:",authCode)
        code = authCode
        data = {
            "clientId": DINGTALK_CLIENT_ID,
            "clientSecret": DINGTALK_CLIENT_SECRET,
            "code":code,
            "grantType":"authorization_code"
        }

        try:
            print("data:",data)
            token_resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
            print("token_resp:",token_resp)
            if "errorCode" in token_resp:
                raise HTTPException(status_code=400,detail=f"钉钉认证失败:{token_resp.get('errorMessage')}")
            accessToken = token_resp.get("accessToken")
            uid = token_resp.get("openId","")
            unionid = token_resp.get("unionId","")
            headers = {"x-acs-dingtalk-access-token":accessToken}
            print("headers:",headers)
            user_resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
            print("user_resp:",user_resp)

            name = user_resp.get("nick","")
            phone = user_resp.get("mobile","")
            avatar = user_resp.get('avatarUrl', '')
            return {
                "uid":uid,
                "name":name,
                "phone":phone,
                "nickname":name,
                "avatar":avatar,
                "unionid":unionid
            }
        except Exception as e:
            raise HTTPException(status_code=500,detail=f"处理钉钉回调时发生错误:{str(e)}")


#产品类

class Product:
    def get_sl_class(self,types):
        # 将类名转换为大写开头
        class_name = types.capitalize()
        current_models = sys.modules[__name__]
        try:
            target_class = getattr(current_models, class_name)
            if issubclass(target_class, Factory):
                return target_class()
        except AttributeError:
                raise ValueError(f"未找到类{class_name}")
        return None



p = Product()